import { useRef } from "react"

// Form状态管理库
class FormStore {
  constructor(){
    // 状态值
    this.store = {}
    // 组件实例
    this.fieldEntities = []
    // 记录回调
    this.callbacks = {}
  }


  setCallbacks = (newCallbacks) => {
    this.callbacks = {
      ...this.callbacks,
      ...newCallbacks
    }
  }

  
  // 存放组件实例 -订阅 & 取消
  registerFieldEntities = (entity) => {
    this.fieldEntities.push(entity)
    return () => {
      this.fieldEntities = this.fieldEntities.filter(
        (_entity ) => _entity !== entity
      )
      delete this.store[entity.props.name]
    }
  }



  // get
  getFieldsValue = () => { // 所有值
    return { ...this.store }
  }
  getFieldValue = (name) => { // 所有单个field值
    return this.store[name]
  }
  // set
  setFieldsValue = (newStore) => {
    // 修改状态库
    this.store = {
      ...this.store,
      ...newStore
    }

    // 更新组件
    this.fieldEntities.forEach(entity => {
      Object.keys(newStore).forEach((k) => { // 只更新修改的相关组件
        if(k === entity.props.name) {
            entity.onStoreChange()
        }
      })
    })
    // console.log('this.store', this.store);
  }

  validate = () => {
    let err = []
    // todo 校验
    return err
  }
  sumbit = () => {
    const { onFinish, onFinishFailed } = this.callbacks
    let err = this.validate()
    if(err.length > 0) {
      // 校验失败 执行 onFinishFailed
      onFinishFailed(this.getFieldsValue(), err)
    } else {
      // 校验成功 执行 onFinish
      onFinish(this.getFieldsValue())
    }
    // 校验成功 执行 onFinish
    // 校验失败 执行 onFinishFailed
    console.log('uuu')
  }

  
  getForm = () => {
    return {
      getFieldsValue: this.getFieldsValue,
      getFieldValue: this.getFieldValue,
      setFieldsValue: this.setFieldsValue,
      registerFieldEntities: this.registerFieldEntities,
      sumbit: this.sumbit,
      setCallbacks: this.setCallbacks,
    }
  }

}


export default function useForm(form) {
  const formRef = useRef() // useRef保证每次传入form对象都是同一个
  if(!formRef.current) {
    if(form) {
      formRef.current = form
    } else {
      const formStore = new FormStore()
      formRef.current = formStore.getForm()
    }
  }
  return [formRef.current]
}